<template>
  <div class="min-h-screen bg-yellow-50">
    <!-- 页面头部 -->
    <header class="border-b border-gray-200">
      <div class="container mx-auto px-4 py-4 sm:py-6">
        <div class="text-center">
          <div class="inline-flex items-center justify-center w-12 h-12 sm:w-16 sm:h-16 bg-gradient-to-r from-yellow-500 to-orange-500 rounded-full mb-3 sm:mb-4 shadow-lg">
            <svg class="w-6 h-6 sm:w-8 sm:h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z"></path>
            </svg>
          </div>
          <h1 class="text-2xl sm:text-3xl lg:text-4xl font-bold bg-gradient-to-r from-gray-900 to-gray-600 bg-clip-text text-transparent">排行榜</h1>
          <p class="text-gray-600 mt-2 text-base sm:text-lg">查看用户排名和积分统计</p>
        </div>
      </div>
    </header>

    <!-- 主要内容区 -->
    <main class="container mx-auto px-4 py-6 max-w-6xl">

      <!-- 筛选和搜索区域 -->
      <div class="bg-white/95 backdrop-blur-sm rounded-2xl shadow-lg p-4 sm:p-6 mb-4 sm:mb-6 border border-gray-200/50">
        <div class="flex flex-col lg:flex-row lg:items-center justify-between gap-4">
          <div class="flex flex-wrap items-center gap-2 sm:gap-3">
            <select
              v-model="selectedPeriod"
              class="px-6 py-3 border border-gray-300 rounded-xl text-sm font-medium text-gray-700 bg-white/80 backdrop-blur-sm hover:bg-gray-50 hover:shadow-md transition-all duration-200 transform hover:scale-105"
              @change="handleFilter"
            >
              <option value="all">全部时间</option>
              <option value="weekly">本周</option>
              <option value="monthly">本月</option>
              <option value="yearly">本年</option>
            </select>
            
            <select
              v-model="selectedType"
              class="px-6 py-3 border border-gray-300 rounded-xl text-sm font-medium text-gray-700 bg-white/80 backdrop-blur-sm hover:bg-gray-50 hover:shadow-md transition-all duration-200 transform hover:scale-105"
              @change="handleFilter"
            >
              <option value="score">积分排行</option>
              <option value="solved">解题数量</option>
              <option value="contests">竞赛排名</option>
            </select>
          </div>

          <div class="flex flex-col sm:flex-row gap-3 w-full sm:w-auto">
            <!-- 搜索框 -->
            <div class="relative flex-grow">
              <input
                v-model="searchQuery"
                type="text"
                placeholder="搜索用户..."
                class="w-full pl-12 pr-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white/80 backdrop-blur-sm transition-all duration-200"
                @input="handleSearch"
              />
              <svg class="absolute left-4 top-3.5 h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
              </svg>
            </div>
          </div>
        </div>
      </div>

      <!-- 排行榜 -->
      <div class="bg-white/95 backdrop-blur-sm rounded-2xl shadow-lg border border-gray-200/50 overflow-hidden">
        <!-- 表头 -->
        <div class="bg-gray-50 px-4 sm:px-6 py-3 border-b border-gray-200">
          <div class="grid grid-cols-12 gap-2 sm:gap-4 text-sm font-medium text-gray-700">
            <div class="col-span-1">排名</div>
            <div class="col-span-4">用户</div>
            <div class="col-span-2 text-center hidden sm:block">积分</div>
            <div class="col-span-2 text-center hidden sm:block">通过题目</div>
            <div class="col-span-2 text-center hidden sm:block">通过率</div>
            <div class="col-span-1 text-center hidden sm:block">活跃度</div>
            <div class="col-span-5 sm:hidden text-center">统计</div>
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="py-12 text-center">
          <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
          <p class="mt-2 text-gray-500">加载中...</p>
        </div>

        <!-- 错误状态 -->
        <div v-else-if="error" class="py-12 text-center">
          <div class="mx-auto w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mb-4">
            <svg class="w-8 h-8 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
            </svg>
          </div>
          <h3 class="text-lg font-semibold text-gray-900 mb-2">加载失败</h3>
          <p class="text-gray-500 mb-4">{{ error }}</p>
          <button 
            @click="loadRankingData"
            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            重试
          </button>
        </div>

        <!-- 排行榜列表 -->
        <div v-else class="divide-y divide-gray-200">
          <div
            v-for="user in (users || [])"
            :key="user.id"
            class="py-4 hover:bg-gray-50 transition-colors duration-150"
          >
            <div class="grid grid-cols-12 gap-2 sm:gap-4 items-center px-4 sm:px-6">
              <!-- 排名 -->
              <div class="col-span-1">
                <div
                  :class="[
                    'w-6 h-6 sm:w-8 sm:h-8 rounded-full flex items-center justify-center text-xs sm:text-sm font-bold',
                    user.rank <= 3 
                      ? user.rank === 1 
                        ? 'bg-yellow-500 text-white' 
                        : user.rank === 2 
                        ? 'bg-gray-400 text-white' 
                        : 'bg-orange-500 text-white'
                      : 'bg-gray-200 text-gray-600'
                  ]"
                >
                  {{ user.rank }}
                </div>
              </div>

              <!-- 用户信息 -->
              <div class="col-span-4 flex items-center space-x-2 sm:space-x-3">
                <img
                  :src="getAvatarUrl(user.id, user.avatar)"
                  :alt="user.username"
                  class="h-8 w-8 sm:h-10 sm:w-10 rounded-full border-2 border-gray-200"
                />
                <div class="min-w-0 flex-1">
                  <h3 class="font-semibold text-gray-900 text-sm sm:text-base truncate">{{ user.username }}</h3>
                  <p class="text-xs sm:text-sm text-gray-500 truncate">
                    {{ user.title || '算法学习者' }}
                    <span :class="['ml-2 text-xs', getLevelColor(user.level)]">{{ user.level_name }}</span>
                  </p>
                </div>
              </div>

              <!-- 桌面端统计 -->
              <div class="col-span-2 text-center hidden sm:block">
                <div class="text-lg font-bold text-blue-600">{{ user.score.toLocaleString() }}</div>
              </div>
              <div class="col-span-2 text-center hidden sm:block">
                <div class="text-lg font-bold text-green-600">{{ user.solved }}</div>
              </div>
              <div class="col-span-2 text-center hidden sm:block">
                <div class="text-lg font-bold text-purple-600">{{ user.acceptance.toFixed(1) }}%</div>
              </div>
              <div class="col-span-1 text-center hidden sm:block">
                <div class="text-sm text-gray-500">{{ formatTime(user.last_active) }}</div>
              </div>

              <!-- 移动端统计 -->
              <div class="col-span-5 sm:hidden text-center">
                <div class="flex justify-center space-x-4 text-xs">
                  <div>
                    <div class="font-bold text-blue-600">{{ user.score.toLocaleString() }}</div>
                    <div class="text-gray-500">积分</div>
                  </div>
                  <div>
                    <div class="font-bold text-green-600">{{ user.solved }}</div>
                    <div class="text-gray-500">通过</div>
                  </div>
                  <div>
                    <div class="font-bold text-purple-600">{{ user.acceptance.toFixed(1) }}%</div>
                    <div class="text-gray-500">通过率</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && !error && (!users || users.length === 0)" class="text-center py-12">
        <div class="mx-auto w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4">
          <svg class="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z"></path>
          </svg>
        </div>
        <h3 class="text-lg font-semibold text-gray-900 mb-2">暂无排名数据</h3>
        <p class="text-gray-500">没有找到符合条件的用户</p>
      </div>

      <!-- 分页 -->
      <div v-if="totalPages > 1" class="mt-6">
        <div class="bg-white/95 backdrop-blur-sm rounded-2xl shadow-lg border border-gray-200/50 p-6">
          <div class="flex items-center justify-between">
            <div class="text-sm text-gray-700">
              显示第
              <span class="font-semibold text-blue-600">{{ (currentPage - 1) * pageSize + 1 }}</span>
              到
              <span class="font-semibold text-blue-600">{{ Math.min(currentPage * pageSize, totalUsers) }}</span>
              条，共
              <span class="font-semibold text-blue-600">{{ totalUsers }}</span>
              条记录
            </div>
            <div class="flex items-center space-x-2">
              <button
                :disabled="currentPage === 1"
                class="relative inline-flex items-center px-4 py-2 rounded-l-xl border border-gray-300 bg-white/80 backdrop-blur-sm text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200"
                @click="goToPage(currentPage - 1)"
              >
                <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                </svg>
                上一页
              </button>
              <button
                v-for="page in visiblePages"
                :key="page"
                :class="[
                  'relative inline-flex items-center px-4 py-2 border text-sm font-medium transition-all duration-200',
                  page === currentPage
                    ? 'z-10 bg-gradient-to-r from-blue-600 to-indigo-600 border-blue-600 text-white shadow-lg'
                    : 'bg-white/80 backdrop-blur-sm border-gray-300 text-gray-500 hover:bg-gray-50'
                ]"
                @click="goToPage(page)"
              >
                {{ page }}
              </button>
              <button
                :disabled="currentPage === totalPages"
                class="relative inline-flex items-center px-4 py-2 rounded-r-xl border border-gray-300 bg-white/80 backdrop-blur-sm text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200"
                @click="goToPage(currentPage + 1)"
              >
                下一页
                <svg class="w-4 h-4 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                </svg>
              </button>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { RankingAPI, type UserRanking, type RankingStats, formatTime, getRankColor, getLevelColor } from '@/api/ranking'
import { getAvatarUrl } from '@/utils'

// 响应式数据
const searchQuery = ref('')
const selectedPeriod = ref('all')
const selectedType = ref('score')
const currentPage = ref(1)
const pageSize = ref(20)
const loading = ref(false)
const error = ref('')

// 真实数据
const users = ref<UserRanking[]>([])
const totalUsers = ref(0)
const totalPages = ref(0)
const stats = ref<RankingStats | null>(null)

// 计算属性
const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, currentPage.value + 2)
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  
  return pages
})

// 方法
const loadRankingData = async () => {
  try {
    loading.value = true
    error.value = ''
    
    console.log('开始加载排行榜数据...', {
      page: currentPage.value,
      page_size: pageSize.value,
      type: selectedType.value,
      period: selectedPeriod.value,
      search: searchQuery.value
    })
    
    const response = await RankingAPI.getRanking({
      page: currentPage.value,
      page_size: pageSize.value,
      type: selectedType.value as 'score' | 'solved' | 'contests',
      period: selectedPeriod.value as 'all' | 'weekly' | 'monthly' | 'yearly',
      search: searchQuery.value || undefined
    })
    
    console.log('API响应数据:', response)
    
    // 检查响应结构并提取数据
    if (response && response.data && response.data.items) {
      users.value = response.data.items
      totalUsers.value = response.data.total || 0
      totalPages.value = response.data.total_pages || 0
      console.log('数据加载成功:', {
        users: users.value.length,
        total: totalUsers.value,
        pages: totalPages.value
      })
    } else {
      console.warn('响应数据格式不正确:', response)
      users.value = []
      totalUsers.value = 0
      totalPages.value = 0
    }
  } catch (err: any) {
    error.value = err.message || '加载排行榜数据失败'
    console.error('加载排行榜数据失败:', err)
    // 确保在错误情况下也有默认值
    users.value = []
    totalUsers.value = 0
    totalPages.value = 0
  } finally {
    loading.value = false
  }
}

const loadStats = async () => {
  try {
    const response = await RankingAPI.getRankingStats()
    console.log('统计信息响应:', response)
    
    // 检查响应结构并提取数据
    if (response && response.data) {
      stats.value = response.data
    } else {
      stats.value = response as any
    }
  } catch (err) {
    console.error('加载统计信息失败:', err)
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadRankingData()
}

const handleFilter = () => {
  currentPage.value = 1
  loadRankingData()
}

const goToPage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    loadRankingData()
  }
}

// 监听分页变化
watch(currentPage, () => {
  loadRankingData()
})

onMounted(() => {
  console.log('组件已挂载，开始加载数据...')
  loadRankingData()
  loadStats()
})
</script>
